<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
  <th:block th:include="include :: header('新增商品')"/>
  <th:block th:include="include :: select2-css"/>
  <th:block th:include="include :: summernote-css"/>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
  <form class="form-horizontal m" id="form-product-add">
    <div class="form-group">
      <label class="col-sm-3 control-label is-required">商品编码：</label>
      <div class="col-sm-8">
        <input name="productCode" class="form-control" type="text" required>
      </div>
    </div>
    <div class="form-group">
      <label class="col-sm-3 control-label">商品名称：</label>
      <div class="col-sm-8">
        <input name="productName" class="form-control" type="text">
      </div>
    </div>
    <div class="form-group">
      <label class="col-sm-3 control-label">显示顺序：</label>
      <div class="col-sm-8">
        <input name="orderNum" class="form-control" type="text">
      </div>
    </div>
    <div class="form-group">
      <label class="col-sm-3 control-label">零售价：</label>
      <div class="col-sm-8">
        <input name="retailPrice" class="form-control" type="text">
      </div>
    </div>
    <div class="form-group">
      <label class="col-sm-3 control-label">实售价：</label>
      <div class="col-sm-8">
        <input name="currentPrice" class="form-control" type="text">
      </div>
    </div>
    <div class="form-group">
      <input name="deptId" type="hidden" id="treeId"/>
      <label class="col-sm-3 control-label is-required">分类：</label>
      <div class="col-sm-8">
        <div class="input-group">
          <input name="categoryName" onclick="selectCategoryTree()" id="treeName" type="text" placeholder="请选择分类" class="form-control"
                 required>
          <span class="input-group-addon"><i class="fa fa-search"></i></span>
        </div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-sm-3 control-label">品牌：</label>
      <div class="col-sm-8">
        <select id="brand" class="form-control select2-multiple" required>
          <option value="">--请选择--</option>
          <option th:each="brand:${brands}" th:value="${brand.brandId}" th:text="${brand.brandName}"
                  th:disabled="${brand.status == '1'}"></option>
        </select>
      </div>
    </div>
<!--    <div class="form-group">-->
<!--      <label class="col-sm-3 control-label">商品介绍：</label>-->
<!--      <div class="col-sm-8">-->
<!--        <input name="introduce" class="form-control" type="text">-->
<!--      </div>-->
<!--    </div>-->
<!--    <div class="form-group">-->
<!--      <label class="col-sm-3 control-label">规格参数：</label>-->
<!--      <div class="col-sm-8">-->
<!--        <input name="specification" class="form-control" type="text">-->
<!--      </div>-->
<!--    </div>-->
    <div class="form-group">
      <label class="col-sm-3 control-label">商品介绍：</label>
      <div class="col-sm-8">
        <div class="introduce">
        </div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-sm-3 control-label">规格参数：</label>
      <div class="col-sm-8">
        <div class="specification">
        </div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-sm-3 control-label">是否上架：</label>
      <div class="col-sm-8">
        <div class="radio-box" th:each="dict : ${@dict.getType('pro_product_is_putaway')}">
          <input type="radio" th:id="${'status_' + dict.dictCode}" name="isPutaway" th:value="${dict.dictValue}"
                 th:checked="${dict.default}">
          <label th:for="${'status_' + dict.dictCode}" th:text="${dict.dictLabel}"></label>
        </div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-sm-3 control-label">是否新品：</label>
      <div class="col-sm-8">
        <div class="radio-box" th:each="dict : ${@dict.getType('pro_product_is_new')}">
          <input type="radio" th:id="${'status_' + dict.dictCode}" name="isNew" th:value="${dict.dictValue}" th:checked="${dict.default}">
          <label th:for="${'status_' + dict.dictCode}" th:text="${dict.dictLabel}"></label>
        </div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-sm-3 control-label">是否推荐：</label>
      <div class="col-sm-8">
        <div class="radio-box" th:each="dict : ${@dict.getType('pro_product_is_recommend')}">
          <input type="radio" th:id="${'status_' + dict.dictCode}" name="isRecommend" th:value="${dict.dictValue}"
                 th:checked="${dict.default}">
          <label th:for="${'status_' + dict.dictCode}" th:text="${dict.dictLabel}"></label>
        </div>
      </div>
    </div>
    <div class="form-group">
      <label class="col-sm-3 control-label">备注：</label>
      <div class="col-sm-8">
        <textarea name="remark" class="form-control"></textarea>
      </div>
    </div>
    <div class="hr-line-dashed"></div>
    <div class="form-group">
      <label class="col-sm-3 control-label">商品类型：</label>
      <div class="col-sm-8">
        <select id="proType" class="form-control select2-multiple" onchange="addCustomFiledSelect()" required>
          <option value="">--请选择--</option>
          <option th:each="type:${types}" th:value="${type.typeId}" th:text="${type.name}"
                  th:disabled="${type.status == '1'}"></option>
        </select>
      </div>
    </div>
  </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: select2-js"/>
<th:block th:include="include :: summernote-js"/>
<script type="text/javascript">
  var prefix = ctx + "product/product"
  $("#form-product-add").validate({
    focusCleanup: true
  });

  /*商品管理-新增-选择分类树*/
  function selectCategoryTree() {
    var url = ctx + "product/category/selectCategoryTree/";
    var options = {
      title: '选择分类',
      width: "380",
      url: url,
      callBack: doSubmit
    };
    $.modal.openOptions(options);
  }

  function findCustomFiled() {
    //商品类型ID
    let proTypeId = $.form.selectSelects("proType");
    if (proTypeId == '') {
      return
    }
    // alert(proTypeId)

    let customFormdata = new FormData();
    customFormdata.append("typeId", proTypeId);
    customFormdata.append("type", 1);

    var data;

    $.ajax({
      url: ctx + "product/customRecord/find",
      type: "post",
      data: customFormdata,
      processData: false,
      contentType: false,
      async: false,
      success: function (result) {
        data = result;
      }
    });
    return data;
  }

  function addCustomFiledSelect() {
    const data = findCustomFiled();

    $(".append").remove();
    $.each(data, function (index, customRecord) {
      let formGroupHtml = '';

      formGroupHtml += '<div class="form-group append">';
      formGroupHtml += '<label class="col-sm-3 control-label">' + customRecord.name + '：</label>';
      formGroupHtml += '<div class="col-sm-8">';
      formGroupHtml += '<select id="customRecord' + customRecord.customRecordId + '" class="form-control select2-multiple" required>';
      formGroupHtml += '<option value="">--请选择--</option>';

      $.each(customRecord.customRecordValues, function (index, customRecordValue) {
        formGroupHtml += '<option value="' + customRecordValue.customRecordValueId + '">' + customRecordValue.name + '</option>';
      });

      formGroupHtml += '</select>';
      formGroupHtml += '</div>';
      formGroupHtml += '</div>';

      $("#form-product-add").append(formGroupHtml);
    });
  }

  function customFiledSelect() {
    //商品类型ID
    let proTypeId = $.form.selectSelects("proType");
    if (proTypeId == '') {
      return
    }
    // alert(proTypeId)

    let customFormdata = new FormData();
    customFormdata.append("typeId", proTypeId);
    customFormdata.append("type", 1);//查询字段的档案

    $.ajax({
      url: ctx + "product/customRecord/find",
      type: "post",
      data: customFormdata,
      processData: false,
      contentType: false,
      success: function (result) {

        $(".append").remove();
        $.each(result, function (index, customRecord) {
          let formGroupHtml = '';

          formGroupHtml += '<div class="form-group append">';
          formGroupHtml += '<label class="col-sm-3 control-label">' + customRecord.name + '：</label>';
          formGroupHtml += '<div class="col-sm-8">';
          formGroupHtml += '<select id="customRecord' + index + '" class="form-control select2-multiple" required>';
          formGroupHtml += '<option value="">--请选择--</option>';

          $.each(customRecord.customRecordValues, function (index, customRecordValue) {
            formGroupHtml += '<option value="' + customRecordValue.customRecordValueId + '">' + customRecordValue.name + '</option>';
          });

          formGroupHtml += '</select>';
          formGroupHtml += '</div>';
          formGroupHtml += '</div>';

          $("#form-product-add").append(formGroupHtml);
        });
      }
    })
  }

  function doSubmit(index, layero) {
    var tree = layero.find("iframe")[0].contentWindow.$._tree;
    if ($.tree.notAllowParents(tree)) {
      var body = layer.getChildFrame('body', index);
      $("#treeId").val(body.find('#treeId').val());
      $("#treeName").val(body.find('#treeName').val());
      layer.close(index);
    }
  }



  $(document).ready(function () {
    $('.introduce').summernote({
      lang: 'zh-CN',
      height: 300,         // set editor height
      callbacks: {
        onImageUpload: function (files) {
          updateFile(files[0], '.introduce');
        }
      }
    });

    $('.specification').summernote({
      lang: 'zh-CN',
      height: 300,         // set editor height
      callbacks: {
        onImageUpload: function (files) {
          updateFile(files[0], '.specification');
        }
      }
    });
  });

  function updateFile(file, clazz) {
    var fileData = new FormData();
    fileData.append("file", file);

    $.ajax({
      url: "/common/upload",
      data: fileData,
      type: "post",
      contentType: false,
      processData: false,
      success: function (result) {
        if (result.code == web_status.SUCCESS) {
          var url = result.url;
          $(clazz).summernote('insertImage', url, 'image name');
        } else if (result.code == web_status.WARNING) {
          $.modal.alertWarning(result.msg)
        } else {
          $.modal.alertError(result.msg);
        }
      }
    });
  }

  function submitHandler() {
    if ($.validate.form()) {

      let formdata = new FormData();
      formdata.append("productCode", $("input[name='productCode']").val());
      formdata.append("productName", $("input[name='productName']").val());
      formdata.append("orderNum", $("input[name='orderNum']").val());
      formdata.append("retailPrice", $("input[name='retailPrice']").val());
      formdata.append("currentPrice", $("input[name='currentPrice']").val());
      formdata.append("categoryId", $("#treeId").val());
      formdata.append("brandId", $.form.selectSelects("brand"));
      formdata.append("introduce", $('.introduce').summernote('code'));
      formdata.append("specification", $('.specification').summernote('code'));
      formdata.append("isPutaway", $("input[name='isPutaway']:checked").val());
      formdata.append("isNew", $("input[name='isNew']:checked").val());
      formdata.append("isRecommend", $("input[name='isRecommend']:checked").val());
      formdata.append("typeId", $.form.selectSelects("proType"));
      formdata.append("remark", $("input[name='remark']").val());

      const customRecords = findCustomFiled();
      if (customRecords != undefined) {
        $.each(customRecords, function (index, customRecord) {

          formdata.append("customRecordValues[" + index + "].customRecordId", customRecord.customRecordId);
          formdata.append("customRecordValues[" + index + "].customRecordValueId",
              $.form.selectSelects("customRecord" + customRecord.customRecordId + ""));
        });
      }

      // let objData = {};

      // formdata.forEach((value, key) => objData[key] = value);
      // alert(JSON.stringify(objData));

      $.ajax({
        url: prefix + "/add",
        type: "post",
        data: formdata,
        processData: false,
        contentType: false,
        success: function (result) {
          $.operate.saveSuccess(result);
        }
      })
    }
  }
</script>
</body>
</html>